package com.smasher.backup.dialog.select.adapter

import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.AppCompatCheckBox
import com.smasher.backup.dialog.R
import com.smasher.backup.dialog.select.delegate.DefaultElementShowDelegate
import com.smasher.backup.dialog.select.delegate.ElementShowDelegate
import com.smasher.backup.dialog.select.listener.OnInternSelectListener
import com.smasher.widget.base.BaseRecyclerViewHolder

open class SelectViewHolder<T>(itemView: View) : BaseRecyclerViewHolder<T>(itemView) {


    private val selectBox: AppCompatCheckBox = itemView.findViewById(R.id.select_box)
    private val name: TextView = itemView.findViewById(R.id.name)
    private val description: TextView = itemView.findViewById(R.id.description)

    private var selected = false
    private var onInternSelectListener: OnInternSelectListener? = null
    private var elementShowDelegate: ElementShowDelegate<T> = DefaultElementShowDelegate<T>()

    fun setSelected(selected: Boolean) {
        this.selected = selected
    }

    fun setOnSingleSelectListener(onInternSelectListener: OnInternSelectListener) {
        this.onInternSelectListener = onInternSelectListener
    }

    fun setElementShowDelegate(elementShowDelegate: ElementShowDelegate<T>) {
        this.elementShowDelegate = elementShowDelegate
    }

    override fun bindView() {
        super.bindView()
        name.text = elementShowDelegate.showMainTitle(mItem)
        description.text = elementShowDelegate.showSubTitle(mItem)
        elementShowDelegate.bindShowingView(mItem, itemView)

        selectBox.isChecked = selected
        selectBox.setOnCheckedChangeListener { _, isChecked ->
            onInternSelectListener?.let {
                if (isChecked) {
                    it.onSelect(mIndex, itemView)
                } else {
                    it.unSelect(mIndex, itemView)
                }
            }
        }

        itemView.setOnClickListener {
            val checked = selectBox.isChecked
            selectBox.isChecked = !checked
        }
    }

}